import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/dashboard/user'
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login/index.vue')
    },
    {
      path: '/dashboard',
      name: 'dashboard',
      component: () => import('@/views/dashboard/index.vue'),
      children: [
        {
          path: 'user',
          name: 'user',
          component: () => import('@/views/user/index.vue')
        },
        {
          path: 'worker',
          name: 'worker',
          component: () => import('@/views/worker/index.vue')
        },
        {
          path: 'order',
          name: 'order',
          component: () => import('@/views/order/index.vue')
        },
        {
          path: 'item',
          name: 'item',
          component: () => import('@/views/item/index.vue')
        }
      ]
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  if (to.path !== '/login' && !token) {
    next('/login')
  } else {
    next()
  }
})

export default router
